<template>
  <div class="dict-page">
    <el-row :gutter="12">
      <!-- 左侧：表列表 + 新建表 -->
      <el-col :span="6">
        <el-card class="dict-card" shadow="never">
          <div class="search-bar">
            <el-input v-model="q.tableName" placeholder="表名" size="small" @keyup.enter.native="loadTables" />
            <el-input v-model="q.comment" placeholder="表注释" size="small" @keyup.enter.native="loadTables" />
            <div class="search-actions">
              <el-button type="primary" size="small" @click="loadTables">查询</el-button>
              <el-button size="small" @click="openCreateTable">新建表</el-button>
            </div>
          </div>
          <el-table :data="tables" size="small" height="calc(100vh - 260px)" @row-click="onSelectTable" border>
            <el-table-column prop="tableName" label="表名" min-width="140" />
            <el-table-column prop="tableComment" label="注释" />
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧：字段设置 + 新增字段 -->
      <el-col :span="18">
        <el-card class="dict-card" shadow="never">
          <template #header>
            <div class="header">
              <div>
                <span class="title">{{ currentTable ? currentTable.tableName : '请选择表' }}</span>
                <span class="sub" v-if="currentTable && currentTable.tableComment"> - {{ currentTable.tableComment }}</span>
              </div>
              <div class="header-actions">
                <el-button size="small" :disabled="!currentTable" @click="openAddColumns">新增字段</el-button>
                <el-button type="primary" size="small" :disabled="!currentTable" @click="saveSettings">保存设置</el-button>
              </div>
            </div>
          </template>

          <el-table :data="fields" size="small" v-loading="loadingFields" border>
            <el-table-column prop="columnName" label="字段" min-width="140" />
            <el-table-column prop="columnType" label="类型" min-width="120" />
            <el-table-column prop="columnComment" label="注释" min-width="180" />
            <el-table-column label="必填" width="70" align="center">
              <template #default="{ row }">
                <el-switch v-model="row.required" :active-value="1" :inactive-value="0" />
              </template>
            </el-table-column>
            <el-table-column label="唯一" width="70" align="center">
              <template #default="{ row }">
                <el-switch v-model="row.uniqueFlag" :active-value="1" :inactive-value="0" />
              </template>
            </el-table-column>
            <el-table-column label="可见" width="70" align="center">
              <template #default="{ row }">
                <el-switch v-model="row.visible" :active-value="1" :inactive-value="0" />
              </template>
            </el-table-column>
            <el-table-column label="字典类型" min-width="160">
              <template #default="{ row }">
                <el-input v-model="row.dictType" placeholder="如 gender,status" />
              </template>
            </el-table-column>
            <el-table-column label="显示标签" min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.label" />
              </template>
            </el-table-column>
            <el-table-column label="排序" width="100" align="center">
              <template #default="{ row }">
                <el-input-number v-model="row.sort" :min="0" :step="1" />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="示例值" width="120">
              <template #default="{ row }">
                <el-button size="small" @click="previewSamples(row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 示例值弹窗 -->
    <el-dialog v-model="sampleVisible" title="示例值" width="500px">
      <el-table :data="samples" size="small" height="300px" border>
        <el-table-column prop="value" label="值" />
        <el-table-column prop="count" label="次数" width="100" />
      </el-table>
    </el-dialog>

    <!-- 新建表弹窗 -->
    <el-dialog v-model="createVisible" title="创建业务表" width="720px">
      <el-form :model="createForm" label-width="90px">
        <el-form-item label="表名">
          <el-input v-model="createForm.tableName" placeholder="如 biz_order" />
        </el-form-item>
        <el-form-item label="表注释">
          <el-input v-model="createForm.comment" />
        </el-form-item>
        <el-form-item label="字段定义">
          <el-table :data="createForm.columns" size="small" border>
            <el-table-column label="字段名" min-width="140">
              <template #default="{ row }"><el-input v-model="row.columnName" /></template>
            </el-table-column>
            <el-table-column label="类型" width="120">
              <template #default="{ row }">
                <el-select v-model="row.dataType" placeholder="类型">
                  <el-option label="varchar" value="varchar" />
                  <el-option label="int" value="int" />
                  <el-option label="bigint" value="bigint" />
                  <el-option label="tinyint" value="tinyint" />
                  <el-option label="decimal" value="decimal" />
                  <el-option label="datetime" value="datetime" />
                  <el-option label="date" value="date" />
                  <el-option label="text" value="text" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="长度" width="100">
              <template #default="{ row }"><el-input-number v-model="row.length" :min="1" /></template>
            </el-table-column>
            <el-table-column label="小数位" width="100">
              <template #default="{ row }"><el-input-number v-model="row.scale" :min="0" /></template>
            </el-table-column>
            <el-table-column label="主键" width="80" align="center">
              <template #default="{ row }"><el-switch v-model="row.primaryKey" /></template>
            </el-table-column>
            <el-table-column label="自增" width="80" align="center">
              <template #default="{ row }"><el-switch v-model="row.autoIncrement" /></template>
            </el-table-column>
            <el-table-column label="非空" width="80" align="center">
              <template #default="{ row }"><el-switch v-model="row.nullable" :active-value="false" :inactive-value="true" /></template>
            </el-table-column>
            <el-table-column label="唯一" width="80" align="center">
              <template #default="{ row }"><el-switch v-model="row.unique" /></template>
            </el-table-column>
            <el-table-column label="注释" min-width="160">
              <template #default="{ row }"><el-input v-model="row.comment" /></template>
            </el-table-column>
            <el-table-column fixed="right" width="80">
              <template #default="{ $index }">
                <el-button type="danger" link @click="removeCreateColumn($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="add-row">
            <el-button type="primary" link @click="addCreateColumn">添加字段</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible=false">取消</el-button>
        <el-button type="primary" @click="submitCreateTable">创建</el-button>
      </template>
    </el-dialog>

    <!-- 新增字段弹窗 -->
    <el-dialog v-model="addVisible" title="新增字段" width="700px">
      <el-table :data="addColumnsForm" size="small" border>
        <el-table-column label="字段名" min-width="140">
          <template #default="{ row }"><el-input v-model="row.columnName" /></template>
        </el-table-column>
        <el-table-column label="类型" width="120">
          <template #default="{ row }">
            <el-select v-model="row.dataType" placeholder="类型">
              <el-option label="varchar" value="varchar" />
              <el-option label="int" value="int" />
              <el-option label="bigint" value="bigint" />
              <el-option label="tinyint" value="tinyint" />
              <el-option label="decimal" value="decimal" />
              <el-option label="datetime" value="datetime" />
              <el-option label="date" value="date" />
              <el-option label="text" value="text" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="长度" width="100">
          <template #default="{ row }"><el-input-number v-model="row.length" :min="1" /></template>
        </el-table-column>
        <el-table-column label="小数位" width="100">
          <template #default="{ row }"><el-input-number v-model="row.scale" :min="0" /></template>
        </el-table-column>
        <el-table-column label="非空" width="80" align="center">
          <template #default="{ row }"><el-switch v-model="row.nullable" :active-value="false" :inactive-value="true" /></template>
        </el-table-column>
        <el-table-column label="唯一" width="80" align="center">
          <template #default="{ row }"><el-switch v-model="row.unique" /></template>
        </el-table-column>
        <el-table-column label="注释" min-width="160">
          <template #default="{ row }"><el-input v-model="row.comment" /></template>
        </el-table-column>
        <el-table-column fixed="right" width="80">
          <template #default="{ $index }">
            <el-button type="danger" link @click="removeAddColumn($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="addVisible=false">取消</el-button>
        <el-button type="primary" @click="submitAddColumns">新增</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import dictionaryApi, { DictField, DictTable } from '@/api/dictionary'
import request from '@/utils/request'

const q = reactive({ tableName: '', comment: '' })
const tables = ref<DictTable[]>([])
const fields = ref<DictField[]>([])
const currentTable = ref<DictTable | null>(null)
const loadingFields = ref(false)

const sampleVisible = ref(false)
const samples = ref<{ value: any; count: number }[]>([])

// 新建表
const createVisible = ref(false)
const createForm = reactive({
  tableName: '',
  comment: '',
  columns: [] as any[]
})

// 新增字段
const addVisible = ref(false)
const addColumnsForm = ref<any[]>([])

async function loadTables() {
  const res = await dictionaryApi.getTables({ tableName: q.tableName, comment: q.comment })
  tables.value = (res.data?.data || res.data || []) as DictTable[]
}

async function onSelectTable(row: DictTable) {
  currentTable.value = row
  loadingFields.value = true
  try {
    const res = await dictionaryApi.getColumns(row.tableName)
    fields.value = (res.data?.data || res.data || []) as DictField[]
    fields.value.forEach(f => {
      f.tableName = row.tableName
      f.required = f.required ?? 0
      f.uniqueFlag = f.uniqueFlag ?? 0
      f.visible = f.visible ?? 1
      f.sort = f.sort ?? 0
    })
  } finally {
    loadingFields.value = false
  }
}

async function saveSettings() {
  if (!currentTable.value) return
  await dictionaryApi.saveFields(fields.value as any)
  ElMessage.success('保存成功')
}

async function previewSamples(row: DictField) {
  if (!currentTable.value) return
  // 简单示例：直接请求后端通用接口查询 TOP 50 频次（此处临时走 SQL 聚合接口，你也可在后端提供专用API）
  const sql = `SELECT \`${row.columnName}\` AS value, COUNT(1) AS count FROM \`${row.tableName}\` GROUP BY \`${row.columnName}\` ORDER BY count DESC LIMIT 50`
  const res = await request.post('/api/sql/preview', { sql })
  samples.value = (res.data?.data || []) as any
  sampleVisible.value = true
}

loadTables()

// UI 交互：创建表/新增字段
function openCreateTable() {
  createForm.tableName = ''
  createForm.comment = ''
  createForm.columns = [
    { columnName: 'id', dataType: 'bigint', primaryKey: true, autoIncrement: true, nullable: false, comment: '主键' }
  ]
  createVisible.value = true
}
function addCreateColumn() { createForm.columns.push({ dataType: 'varchar', length: 50, nullable: true }) }
function removeCreateColumn(index: number) { createForm.columns.splice(index, 1) }
async function submitCreateTable() {
  if (!createForm.tableName) { ElMessage.error('请输入表名'); return }
  await dictionaryApi.createTable(createForm.tableName, createForm.columns, createForm.comment)
  ElMessage.success('创建成功')
  createVisible.value = false
  loadTables()
}

function openAddColumns() {
  if (!currentTable.value) return
  addColumnsForm.value = [ { dataType: 'varchar', length: 50, nullable: true } ]
  addVisible.value = true
}
function removeAddColumn(index: number) { addColumnsForm.value.splice(index, 1) }
async function submitAddColumns() {
  if (!currentTable.value) return
  await dictionaryApi.addColumns(currentTable.value.tableName, addColumnsForm.value)
  ElMessage.success('新增字段成功')
  addVisible.value = false
  onSelectTable(currentTable.value)
}
</script>

<style lang="scss" scoped>
.dict-page {
  .dict-card { margin-bottom: 12px; }
  .search-bar { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px; }
  .search-actions { grid-column: 1 / span 2; display: flex; gap: 8px; }
  .header { display: flex; justify-content: space-between; align-items: center; }
  .title { font-weight: 600; }
  .sub { color: var(--el-text-color-secondary); margin-left: 6px; }
  .add-row { margin-top: 6px; }
}
</style>


